// google-sheets.js
const { google } = require('googleapis');
const path = require('path');
const config = require('../config');
// 1. 加载服务账号密钥
const auth = new google.auth.GoogleAuth({
    keyFile: path.join(__dirname, './tactical-hope-462303-k6-81c9e322dc1d.json'), // 改成你服务器的路径
    scopes: ['https://www.googleapis.com/auth/spreadsheets'], // 读写权限
});


/**
 * @param {*} range 
 * @returns 
 */
async function readSheet (range) {
    try {
        // console.log('开始读取数据...');
        const client = await auth.getClient();
        const sheets = google.sheets({ version: 'v4', auth: client });
        const spreadsheetId = config.googleSheets.spreadsheetId; // URL 中 /d/xxx/ 那个 xxx
        // const range = 'birthDate' //config.googleSheets.sheetName;
        const res = await sheets.spreadsheets.values.get({
            spreadsheetId,
            range,
        });
        // console.log('读取数据:', res);
        return res.data.values
    } catch (error) {
        return error
    }
}
/**
 * @param {*} range 
 * @param {*} values 
 * @returns 
 */
async function writeSheet (range, values) {
    const client = await auth.getClient();
    const sheets = google.sheets({ version: 'v4', auth: client });

    const spreadsheetId = config.googleSheets.spreadsheetId;

    const res = await sheets.spreadsheets.values.append({
        spreadsheetId,
        range,
        valueInputOption: 'RAW',
        requestBody: {
            values,
        },
    });

    return res.data
}
/**
 * 
 * @param {*} range 
 * @param {*} values 
 * @returns 
 */
async function updateSheet (range, values) {
    const client = await auth.getClient();
    const sheets = google.sheets({ version: 'v4', auth: client });

    const spreadsheetId = config.googleSheets.spreadsheetId;

    const res = await sheets.spreadsheets.values.update({
        spreadsheetId,
        range,
        valueInputOption: 'RAW',
        requestBody: {
            values,
        },
    });
    return res.data
}

module.exports = {
    readSheet,
    writeSheet,
    updateSheet
}